import '../../util/_base_export.dart';
import '../../util/_view_export.dart';

//import 'package:google_places_flutter/google_places_flutter.dart';
//import 'package:google_places_flutter/model/prediction.dart';
import "package:google_maps_webservice/geocoding.dart";
import "package:flutter_google_places/flutter_google_places.dart";

import 'package:geolocator/geolocator.dart';

import '../../util/app_util.dart';
import '../../blocs/cart.dart';
import '../../blocs/profile.dart';
import '../../blocs/helper.dart';
// import 'dart:convert' as JSON;
// // import 'package:meta/meta.dart';
// // import 'package:equatable/equatable.dart';
// import 'package:http/http.dart' as Http;

class AccountAddressPage extends StatefulWidget {
  @override
  _AccountAddressPageState createState() => new _AccountAddressPageState();
}

class _AccountAddressPageState extends State<AccountAddressPage> {
  ProfileBloc? lb_profile;
  HelperBloc? lb_helper;

  GlobalKey<FormBuilderState> _fbKey = GlobalKey<FormBuilderState>();

  CancelFunc? cancelLoading;
  _fetchGeocodingPlace(String placeId) async {
    final geocoding = new GoogleMapsGeocoding(apiKey: App3rdKey.googlemap_key);
    GeocodingResponse response = await geocoding.searchByPlaceId(placeId);
    AppSession.currentLocation['lat'] = response.results[0].geometry.location.lat;
    AppSession.currentLocation['lng'] = response.results[0].geometry.location.lng;

    print(AppSession.currentLocation['lat']);
    print(AppSession.currentLocation['lng']);
    print(response.results[0].geometry.location.lat);
    print(response.results[0].postcodeLocalities);
    print(response.results[0].addressComponents[0]);
    print(response.results[0].addressComponents[0].longName);
    print(response.results[0].formattedAddress);
  }

  _fetchGeocodingLocation() async {
    final geocoding = new GoogleMapsGeocoding(apiKey: App3rdKey.googlemap_key);
    GeocodingResponse response = await geocoding.searchByLocation(
        Location(lat:AppSession.currentLocation['lat'], lng:AppSession.currentLocation['lng']));
    print(response.results[0].geometry.location.lat);
    print(response.results[0].postcodeLocalities);
    print(response.results[0].addressComponents[0]);
    print(response.results[0].addressComponents[0].longName);
    print(response.results[0].formattedAddress);
    controller.text = response.results[0].formattedAddress??'';
    controller.selection = TextSelection.fromPosition(
        // TextPosition(offset: response.results[0]?.formattedAddress.length));
        TextPosition(offset: 0));

    // print(response.toString());
  }

  _initLocation() async {
    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best);
    AppSession.currentLocation['lat'] = position.latitude;
    AppSession.currentLocation['lng'] = position.longitude;
    print(AppSession.currentLocation);
    await _fetchGeocodingLocation();
  }
  // final String apiKey = 'AIzaSyDm0bF_bjpEue3XwywDxx5_2J67jdIF6FU';
  // final String language = 'en';
  // final String BASE_GEOLOCATION_API = 'https://maps.googleapis.com/maps/api/geocode/json';
  // final String BASE_PLACES_API = 'https://maps.googleapis.com/maps/api/place/details/json';

  // Future<Geolocation> getGeolocation(
  //     {@required String placeId, String sessionToken, List<String> fields}) async {
  //   print('aaaa');
  //   var response = await Http.post(
  //     BASE_GEOLOCATION_API,
  //     body: JSON.jsonEncode(<String, String>{
  //       'place_id': placeId,
  //       // 'langage': language,
  //       // 'fields': fields,
  //       // 'sessionToken': sessionToken,
  //       // 'key': apiKey,
  //     }),
  //   );
  //   print(response.toString());

  //   var json = JSON.jsonDecode(response.body);
  //   print(json);
  //   if (json['status'] != 'OK') {
  //     print(json);
  //     // switch (json['status']) {
  //     //   case 'UNKNOWN_ERROR':
  //     //     throw ServerException();
  //     //   case 'ZERO_RESULTS':
  //     //   case 'NOT_FOUND':
  //     //     throw ZeroResultsException();
  //     //   case 'OVER_QUERY_LIMIT':
  //     //     throw OverLimitException();
  //     //   case 'REQUEST_DENIED':
  //     //     throw UnauthorizedException();
  //     // }
  //   }
  //   print(Geolocation.fromJSON(json));
  //   // return Geolocation.fromJSON(json);
  //   // Geolocation geolocation = await getGeolocation(placeId: placeId);
  // }

  @override
  initState() {
    super.initState();
    lb_profile = context.read<ProfileBloc>();
    lb_helper = context.read<HelperBloc>();
    // if ((AppSession.userAddr ?? {}).isNotEmpty) controller.text = AppSession.userAddr['addr'];
    if (AppSession.addrEdit.isNotEmpty) controller.text = AppSession.addrEdit['addr'];
  }

  placesAutoCompleteTextField() {
    // return PlacesAutocompleteFormField(
    //     // textStyle:
    //     controller: controller,
    //     apiKey: App3rdKey.googlemap_key,
    //     inputDecoration: InputDecoration(),
    //     onSaved: (Prediction prediction) async {
    //       print(prediction.placeId);
    //       await _fetchGeocodingPlace(prediction.placeId);
    //       controller.text = prediction.description;
    //
    //       controller.selection = TextSelection.fromPosition(TextPosition(
    //         // offset: prediction.description.length,
    //         offset: 0,
    //       ));
    //     }
    //     // default 600 ms ,
    //     );
  }

  TextEditingController controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    print(AppSession.userAddr);

    // var init_addr = {
    //   'unit': AppSession.addrEdit['unit'] ?? '',
    //   'postal': AppSession.addrEdit['postal'] ?? '',
    //   'buzz': AppSession.addrEdit['buzz'] ?? '',
    //   'consignee_name': AppSession.addrEdit['consignee_name'] ?? '',
    //   'consignee_phone': AppSession.addrEdit['consignee_phone'] ?? '',
    // };
    return Material(
      child: Scaffold(
        appBar: AppBar(
          brightness: Brightness.light,
          leading: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              Navigator.pop(context);
            },
            child: Container(
              child: Icon(
                Icons.chevron_left,
                color: AppColor.blackMain,
                size: 32,
              ),
            ),
          ),
          title: Text('地址维护', style: TextStyle(color: AppColor.blackMain)),
        ),
        body: SingleChildScrollView(
          child: Container(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                SizedBox(height: 20),
                FormBuilder(
                  // context,
                  key: _fbKey,
                  autovalidateMode: AutovalidateMode.always,
                  initialValue: AppSession.addrEdit,
                  enabled: false,
                  child: Column(
                    children: <Widget>[
                      Container(
                        // decoration: AppDecoration.buttonTwo, //
                        margin: EdgeInsets.symmetric(horizontal: 35.w),
                        padding: EdgeInsets.only(
                          left: 10.w,
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Text('请输入地址:'),
                            TextButton(
                              onPressed: () async {
                                cancelLoading =
                                    BotToast.showLoading(duration: Duration(seconds: 15));
                                await _initLocation();
                                // Position position = await Geolocator()
                                //     .getCurrentPosition(desiredAccuracy: LocationAccuracy.best);
                                // AppSession.currentLocation['lat'] = position?.latitude ?? 0.0;
                                // AppSession.currentLocation['lng'] = position?.longitude ?? 0.0;
                                cancelLoading!();
                              },
                              child: Row(
                                children: <Widget>[
                                  Icon(
                                    // MaterialCommunityIcons.map_marker_radius,
                                    Icons.map_rounded,
                                    size: 24,
                                    color: AppColor.yellowText,
                                  ),
                                  Text(
                                    '自动获取',
                                    style: TextStyle(
                                      color: AppColor.yellowText,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        // decoration: AppDecoration.buttonTwo, //
                        margin: EdgeInsets.symmetric(horizontal: 35.w),
                        padding: EdgeInsets.only(
                          left: 10.w,
                        ),
                        child: placesAutoCompleteTextField(),
                      ),
                      Container(
                        // decoration: AppDecoration.buttonTwo, //
                        margin: EdgeInsets.symmetric(horizontal: 35.w),
                        padding: EdgeInsets.only(
                          left: 10.w,
                        ),
                        child: FormBuilderTextField(
                          name: "postal",
                          decoration: InputDecoration(
                            // border: AppInput.loginInputBorder,
                            labelText: "邮编 Postal",
                          ),
                          // onChanged: _onChanged,
                          // valueTransformer: (text) => num.tryParse(text),
                          validator: (value){
                             if((value??'').isEmpty){
                               return 'validator：Please enter 邮编 Postal';
                             }
                             return null;
                          },
                          keyboardType: TextInputType.text,
                        ),
                      ),
                      Container(
                        // decoration: AppDecoration.buttonTwo, //
                        margin: EdgeInsets.symmetric(horizontal: 35.w),
                        padding: EdgeInsets.only(
                          left: 10.w,
                        ),
                        child: FormBuilderTextField(
                          name: "unit",
                          decoration: InputDecoration(
                            // border: AppInput.loginInputBorder,
                            labelText: "门牌号 Unit, Condo 必须填写",
                          ),
                          // onChanged: _onChanged,
                          // valueTransformer: (text) => num.tryParse(text),
                          keyboardType: TextInputType.text,
                        ),
                      ),
                      Container(
                        // decoration: AppDecoration.buttonTwo, //
                        margin: EdgeInsets.symmetric(horizontal: 35.w),
                        padding: EdgeInsets.only(
                          left: 10.w,
                        ),
                        child: FormBuilderTextField(
                          name: "buzz",
                          decoration: InputDecoration(
                            // border: AppInput.loginInputBorder,
                            labelText: "公寓密码,非必填",
                          ),
                          // onChanged: _onChanged,
                          // valueTransformer: (text) => num.tryParse(text),
                          keyboardType: TextInputType.text,
                        ),
                      ),
                      Container(
                        // decoration: AppDecoration.buttonTwo, //
                        margin: EdgeInsets.symmetric(horizontal: 35.w),
                        padding: EdgeInsets.only(
                          left: 10.w,
                        ),
                        child: FormBuilderTextField(
                          name: "consignee_name",
                          decoration: InputDecoration(
                            // border: AppInput.loginInputBorder,
                            labelText: "联系人",
                          ),
                          // onChanged: _onChanged,
                          // valueTransformer: (text) => num.tryParse(text),
                          validator: (value){
                              if((value??'').isEmpty){
                                return "联系人不能为空";
                              }
                              return null;
                          },
                          keyboardType: TextInputType.text,
                        ),
                      ),
                      Container(
                        // decoration: AppDecoration.buttonTwo, //
                        margin: EdgeInsets.symmetric(horizontal: 35.w),
                        padding: EdgeInsets.only(
                          left: 10.w,
                        ),
                        child: FormBuilderTextField(
                          name: "consignee_phone",
                          decoration: InputDecoration(
                            // border: AppInput.loginInputBorder,
                            labelText: "联系电话",
                          ),
                          // onChanged: _onChanged,
                          // valueTransformer: (text) => num.tryParse(text),
                          validator: (value){
                            if((value??'').isEmpty){
                              return '联系电话不能为空';
                            }else if(value!.length<9||value.length>11){
                              return '联系电话错误';
                            }else{
                              return null;
                            }
                          },
                          keyboardType: TextInputType.phone,
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.symmetric(horizontal: 35.w),
                        padding: EdgeInsets.only(
                          left: 10.w,
                        ),
                        child: FormBuilderSwitch(
                          name: "is_default",
                          title: Text('设为默认'),
                          initialValue: (AppSession.addrEdit['is_default'] == 1),
                          // decoration: InputDecoration(
                          //   // border: AppInput.loginInputBorder,
                          //   labelText: "联系电话",
                          // ),
                          // onChanged: _onChanged,
                          // valueTransformer: (text) => num.tryParse(text),
                        ),
                      ),
                      SizedBox(
                        height: 30.h,
                      ),
                      Container(
                        margin: const EdgeInsets.only(top: 16.0),
                        child: TextButton(
                          onPressed: () async {
                            FocusScope.of(context).requestFocus(FocusNode());
                            Map<String, dynamic> lm_addr_param = {};
                            if (controller.text.isEmpty) {
                            } else {
                              _fbKey.currentState?.save();
                              if (_fbKey.currentState!.validate()) {
                                lm_addr_param['addr'] = controller.text;
                                lm_addr_param['lat'] =
                                    AppSession.currentLocation['lat']; //AppSession.addrEdit['lat'];
                                lm_addr_param['lng'] =
                                    AppSession.currentLocation['lng']; //AppSession.addrEdit['lng'];
                                lm_addr_param['unit'] = _fbKey.currentState?.value['unit'] ?? '';
                                lm_addr_param['postal'] = _fbKey.currentState?.value['postal'] ?? '';
                                lm_addr_param['buzz'] = _fbKey.currentState?.value['buzz'] ?? '';
                                lm_addr_param['consignee_name'] =
                                    _fbKey.currentState?.value['consignee_name'];
                                lm_addr_param['consignee_phone'] =
                                    _fbKey.currentState?.value['consignee_phone'];
                                lm_addr_param['is_default'] =
                                    (_fbKey.currentState?.value['is_default']) ? 1 : 0;
                                if (AppSession.addrEdit['uaid'] != null)
                                  lm_addr_param['uaid'] = AppSession.addrEdit['uaid'];
                              }
                              // Map<String, dynamic> lm_addr_param = AppSession.userAddr;
                              // {
                              //   "addr": controller.text,
                              //   "lat": AppSession.currentLocation['lat'],
                              //   "lng": AppSession.currentLocation['lng'],
                              //   "unit": _fbKey.currentState.value['unit'],
                              //   "postal": _fbKey.currentState.value['postal'],
                              //   "buzz": _fbKey.currentState.value['buzz'],
                              //   "consignee_name": _fbKey.currentState.value['consignee_name'],
                              //   "consignee_phone": _fbKey.currentState.value['consignee_phone'],
                              // };
                              print(lm_addr_param);
                              var lm_result = await lb_profile?.addrMaintain(lm_addr_param);

                              if ((lm_result ?? {}).isNotEmpty) {
                                if ((lm_result['ev_error'] == 0) &&
                                    ((lm_result['ev_result'] ?? {}).isNotEmpty)) {
                                  print(lm_result['ev_result']['user_address']['wh_id']);
                                  await AppSession.setWhid(
                                      lm_result['ev_result']['user_address']['wh_id']);
                                  print(AppSession.wh_id);
                                  if ((Provider.of<CartBloc>(context, listen: false).ticket)
                                      .isNotEmpty) {
                                    Map<String, dynamic> lm_cart_param = {
                                      'uaid': lm_result['ev_result']['uaid']
                                    };

                                    var lv_result =
                                        await Provider.of<CartBloc>(context, listen: false)
                                            .checkoutUpdate(lm_cart_param);

                                    if (lv_result) {
                                      AppSession.userAddr =
                                          Provider.of<CartBloc>(context, listen: false)
                                              .ticket['user_address'];
                                      lb_helper?.addrUpdate(AppSession.userAddr);
                                    }
                                  } else {
                                    // AppSession.userAddr = lm_result['ev_result']['user_address'];
                                  }

                                  if ((lm_result['ev_result']['popup_msg'] ?? {}).isEmpty) {
                                    AppPopupService.showAlertSimple('S', '更新成功', '',
                                        iv_duration: Duration(seconds: 3));
                                  } else {
                                    AppPopupService.showAlertSimple(
                                        'E',
                                        lm_result['ev_result']['popup_msg']['text'],
                                        '我们会尽快拓展配送范围，早日服务到您',
                                        iv_duration: Duration(seconds: 3));
                                  }
                                  // await Provider.of<ProductBloc>(context, listen: false)
                                  //     .refresh(true);
                                }
                                // final app_util = new AppUtil();
                                await AppSession.appUtil.initLoad();
                                await lb_profile?.addrList();
                                Navigator.pop(context);
                                //   App.router.navigateTo(context, AppRoutes.appMain,
                                //       replace: true, clearStack: true);
                                // }
                              } else {
                                print('sss');
                              }
                            }
                          },
                          child: Container(
                            width: 150.w,
                            height: 50.h,
                            decoration: AppDecoration.buttonOne,
                            child: Center(
                              child: Text(
                                '更新',
                                style: TextStyle(
                                  // color: AppColor.goldenTwo,
                                  fontWeight: FontWeight.w400,
                                  fontSize: 18.sp,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
